import Vue from 'vue'
import Vuex from 'vuex'
import geo from './modules/geo'
import home from './modules/home'

Vue.use(Vuex) // 使用vuex

const store = () => new Vuex.Store({
  modules: {
    geo,
    home
  },
  actions: {
    async nuxtServerInit ({
      commit
    }, { req, app }) {
      // 从服务端取当前定位的城市
      const { status, data: { province, city } } = await app.$axios.get('/geo/getPosition')
      commit('geo/setPosition', status === 200 ? { city, province } : { city: '', province: '' })
      // 从服务端取菜单数据----status必须和返回的字段一致，status1是为了解决命名冲突取的别名
      const { status: status1, data: { menu } } = await app.$axios.get('/geo/menu')
      commit('home/setMenu', status1 === 200 ? menu : [])
      // 从服务端取热门推荐数据
      const { status: status2, data: { result } } = await app.$axios.get('/search/hotPlace', {
        params: {
          city: app.store.state.geo.position.city.replace('市', '')
        }
      })
      commit('home/setHotPlace', status2 === 200 ? result : [])
    }
  }
})
export default store
